import React from 'react'
import { Button, Form, Modal,Input, message } from "antd"
import {useEffect, useState} from 'react'
import request from '../../api';

const AccountManagemenet = ()=>{
    const [username, setUsername] = useState(null);
    const [isEdit, setIsEdit] = useState(false);

    const [form] = Form.useForm();
    
useEffect(()=>{
    const UserInfo = localStorage.getItem('gamer-info')

    if (UserInfo){
        const parsedUserInfo = JSON.parse(UserInfo);
        setUsername(parsedUserInfo.userInfo.user_id);
    }
},[])

const handleChange = ()=>{
    setIsEdit(true)
}

const validatePasswords = async (_, value) => {
    const { new_password } = await form.getFieldsValue();
    if (!value) {
      return Promise.reject('请确认密码');
    } else if (value !== new_password) {
      return Promise.reject('两次输入的密码不一致');
    } else {
      return Promise.resolve();
    }
  };


const onCancel = ()=>{
    form.resetFields()
    setIsEdit(false)
}

  const onOk = ()=>{
    form.validateFields().then(()=>{
        changePassword({
            "new_password": form.getFieldValue("new_password"),
        })
        setIsEdit(false)
    })
  }

  const changePassword = async (param)=>{
    request.changePassword(param).then(res => {
        if (res.status == 200) {
            message.success("修改密码成功")
        }
    })
  }
    
 return (
    <>
        <div style={{padding:20}}>
            <div>
                用户名： {username}
            </div>
            <div style={{marginTop:15}}>
                <Button type="primary" onClick={handleChange}>修改密码</Button>
            </div>
        </div>
        <Modal open={isEdit} onCancel={onCancel} onOk={onOk}>
            <Form form={form} style={{marginTop:30}}>
                <Form.Item 
                    name='new_password' 
                    label='新密码' 
                    rules={[{ required: true, message: '请输入新密码' }]}
                >
                    <Input.Password
                      type="password"
                      placeholder="请输入新密码" 
                      style={{width:350}}

                    />
                </Form.Item>
                <Form.Item 
                    name='again_new_password' 
                    dependencies={['new_password']}
                    validateDebounce={2000} // 改变校验频率
                    // validateTrigger="onBlur"
                    rules={[
                        { validator: validatePasswords, }
                    ]}
                    style={{ marginLeft: 65 }}
                >
                    <Input.Password
                      type="password"
                      placeholder="确认新密码" 
                      style={{width:350}}

                    />
                </Form.Item>
            </Form>

        </Modal>
    </>
 )
}

export default AccountManagemenet